package ans.p17;




import test.Entrance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * #      17
 * 名称   电话号码的字母组合
 * 链接   https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
 * 题解   [2182](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution)
 * 通过率 56.3%
 * 难道   中等
 */

public class Solution {
    @Entrance
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuilder());
        return combinations;

    }

    private void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuilder sb) {
        if (index == digits.length() && sb.length() > 0) {
            combinations.add(sb.toString());
            return;
        }
        char c = digits.charAt(index);
        String s = phoneMap.get(c);
        if (null != s) {
            for (char c1 : s.toCharArray()) {
                sb.append(c1);
                backtrack(combinations, phoneMap, digits, index + 1, sb);
                sb.deleteCharAt(sb.length() - 1);
            }

        }
    }


}
